package com.rc.web.client;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.http.HttpHeaders;

import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.CountDownLatch;


/**
 * 文字生成语言的websocket的连接
 */
public class TtsWebSocketClient extends WebSocketClient {

    // 修改初始化缓冲区大小为 100KB
    private final ByteArrayOutputStream audioData = new ByteArrayOutputStream(102400);
    private final CountDownLatch latch = new CountDownLatch(1);
    private final String text;
    private  String vcn;
    private  String timbre;
    private boolean isConnected = false; // 新增连接状态标记

    public TtsWebSocketClient(URI serverUri, String text, HttpHeaders headers, String vcn, String timbre) {
        super(serverUri);
        this.text = text;
        this.vcn = vcn;
        this.timbre=timbre;
        // 手动设置 WebSocket 头
        if (headers != null) {
            headers.forEach((key, values) -> {
                if (values != null && !values.isEmpty()) {
                    this.addHeader(key, values.get(0));
                }
            });
        }
    }

    public boolean connectBlocking() throws InterruptedException {
        boolean connected = super.connectBlocking();
        System.out.println("websocket连接状态为：" + connected);
        return connected && isConnected; // 返回连接状态
    }

    @Override
    public void onOpen(ServerHandshake handshake) {
        isConnected = true;
        System.out.println("WebSocket 连接成功，准备发送请求...");
        sendTextMessage();
    }

    @Override
    public void onMessage(String message) {
        System.out.println("接收到消息: " + message);
        processResponse(message);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("WebSocket 连接关闭，代码: " + code + ", 原因: " + reason);
        isConnected = false;
        latch.countDown();
    }


    @Override
    public void onError(Exception ex) {
        ex.printStackTrace();
    }

    private void sendTextMessage() {
        JsonObject payload = new JsonObject();
        payload.addProperty("aue", 0); // PCM
        payload.addProperty("auf", "audio/L16;rate=24000");
        if(vcn.equals("0")){
            payload.addProperty("vcn",this.timbre);
        }else {
            payload.addProperty("vcn", this.vcn);
        }
        payload.addProperty("speed", 43);
        payload.addProperty("volume", 100);
        payload.addProperty("text", Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8)));
        payload.addProperty("encoding", "utf8");
        payload.addProperty("reqId", System.currentTimeMillis());
        send(payload.toString());
    }

    private void processResponse(String message) {
        try {
            System.out.println("处理响应: " + message);
            JsonObject response = JsonParser.parseString(message).getAsJsonObject();
            
            // 处理握手成功消息
            if (response.has("error_code") && response.get("error_code").getAsInt() == 0) {
                System.out.println("WebSocket 握手成功");
                if (!response.has("data")) return; // 如果没有 data 字段则返回
            }

            // 处理音频数据消息
            if (response.has("data")) {
                JsonObject data = response.getAsJsonObject("data");
                if (data.has("audio")) {
                    String audio = data.get("audio").getAsString();
                    if (audio != null && !audio.isEmpty()) { // 检查 audio 字段是否为空
                        System.out.println("接收到音频数据长度: " + audio.length());
                        byte[] decodedAudio = Base64.getDecoder().decode(audio);
                        System.out.println("解码后音频数据长度: " + decodedAudio.length);
                        audioData.write(decodedAudio, 0, decodedAudio.length);
                    }
                }

                if (data.has("status") && data.get("status").getAsInt() == 2) {
                    System.out.println("音频数据接收完成，等待服务端关闭连接...");
                    latch.countDown(); // 释放 latch
                }
            }
        } catch (Exception e) {
            System.err.println("处理响应时发生异常: " + e.getMessage());
            e.printStackTrace();
            latch.countDown(); // 异常时也释放 latch
        }
    }

    public byte[] getAudioData() throws InterruptedException {
        latch.await(); // 移除 TimeUnit
        byte[] data = audioData.toByteArray();
        
        // 打印音频数据长度和部分内容
        System.out.println("获取到的音频数据长度: " + data.length + " 字节");
        if (data.length > 0) {
            System.out.println("音频数据前 16 字节: " + bytesToHex(data, 16));
        }
        
        return data;
    }

    // 辅助方法：将字节数组转换为十六进制字符串
    private String bytesToHex(byte[] bytes, int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Math.min(bytes.length, length); i++) {
            sb.append(String.format("%02X ", bytes[i]));
        }
        return sb.toString();
    }
}